const User =  require('../models/System/User')
const https = require('https')
module.exports = options => async (req,res,next)=>{
    // 获取用户登录Ip,百度地图api
    // 获取地址 https://api.map.baidu.com/location/ip?ak=您的AK&ip=您的IP&coor=bd09ll //HTTPS协议
    let ip = req.headers['x-forwarded-for'] ||
    req.connection.remoteAddress ||
    req.socket.remoteAddress ||
    req.connection.socket.remoteAddress;
    let option = {
        hostname:"api.map.baidu.com",//接口域名
        path:`/location/ip?ip=${ip}&ak=IjlQyeDxGb3QGxhcD7Wsik6UISYieSLt`,//path格式
        headers:{//设置请求头
            "Content-Type":"application/json; charset=utf-8",
            "Authorization": "APPCODE 4390f21526a64f3c99bca6260b9f295d",
        }
    };
    console.log(ip);
    // ip信息
    const ipInfo = {}
    const post_req = await https.request(option, async (Res)=>{
        Res.setEncoding('utf8');
        if(Res.statusCode===200){//若http状态码为200则请求成功
            Res.on('data',async (data) => {
                if(JSON.parse(data).status === 0){
                    const {province , city} = JSON.parse(data).content.address_detail
                    console.log(JSON.parse(data));
                    ipInfo.userSite= province  + " " + city
                    ipInfo.userCity= city
                    ipInfo.userIp = ip
                }else{
                    ipInfo.userSite= '内网IP'
                    ipInfo.userCity= ''
                    ipInfo.userIp = ip
                }
                req.user = ipInfo
                await next()
            });
        }else{
            ipInfo.userSite= '内网IP'
            ipInfo.userCity= ''
            ipInfo.userIp = ip
            req.user = ipInfo
            await next()
        }
    })
    post_req.end();
}
    